package hc.j2me.ui;

import hc.core.util.MsgNotifier;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class MsgDisper {
	private int maxLineSize, pixelBetweenLine = 1, usedLine, msgLineHeight;
	private int width;
	
	public void init(int msgLineHeight, int maxLineSize, int width, Graphics g){
		this.msgLineHeight = msgLineHeight;
		this.maxLineSize = maxLineSize;
		this.width = width;
		this.notifyG = g;
	}
	
	public boolean printNextMsg(){
		String lineMsg = MsgNotifier.getInstance().getNextMsg();
		if(lineMsg != null){
			int idx_newline = -1;
			while((idx_newline = lineMsg.indexOf("\n")) >= 0){
				printLine(lineMsg.substring(0, idx_newline), width);
				lineMsg = lineMsg.substring(idx_newline + 1);
			}
			printLine(lineMsg, width);
			return true;
		}else{
			return false;
		}
	}

	private Graphics notifyG;

	private boolean isAZ(final char c){
		if((c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z')){
			return true;
		}else{
			return false;
		}
	}
	
	private void printLine(String lineMsg, final int screenWidth) {
		if(notifyG.getFont().stringWidth(lineMsg) < screenWidth){
			printPhyLine(lineMsg);
		}else{
			final Font font = notifyG.getFont();
			char[] chars = lineMsg.toCharArray();
			final int maxLen = chars.length;
			int start_idx = 0;
			int split_idx = maxLen;
			while(start_idx < maxLen){
				while(font.charsWidth(chars, start_idx, split_idx - start_idx) > screenWidth){
					split_idx--;
				}
				
				//以空格居尾
				while((split_idx > start_idx) 
						&& (split_idx != maxLen && isAZ(chars[split_idx])) 
						&& isAZ(chars[split_idx - 1])){
					split_idx--;
				}
				String splitStr = new String(chars, start_idx, split_idx - start_idx);
				printPhyLine(splitStr);
				start_idx = split_idx;
				split_idx = maxLen;
			}
		}
	}

	private void printPhyLine(String lineMsg) {
		if(lineMsg.length() == 0){
			return;
		}
		
		// 将进度信息输出到屏幕提示
		if(usedLine == maxLineSize){
		    int idx_y = msgLineHeight * (--usedLine);
			notifyG.copyArea(0, msgLineHeight, 
					width, idx_y, 0, 0, Graphics.TOP|Graphics.LEFT);
			
			notifyG.setColor(0xcc807039);
			notifyG.fillRect(0, idx_y, width, msgLineHeight);
		}
		
		notifyG.setColor(102,255,0);
		notifyG.drawString(lineMsg, 2, msgLineHeight * (usedLine++) + pixelBetweenLine, Graphics.TOP|Graphics.LEFT);
	}

}
